package com.zhentao.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.zhentao.model.wemedia.dto.WmNewsDownOrUpDto;

import com.zhentao.schedule.model.common.dtos.PageResponseResult;
import com.zhentao.schedule.model.common.dtos.ResponseResult;
import com.zhentao.schedule.model.common.enums.AppHttpCodeEnum;
import com.zhentao.schedule.utils.wemedia.WmThreadLocalUtil;
import com.zhentao.domain.WmNewsMaterial;
import com.zhentao.dto.WmNewsDto;
import com.zhentao.dto.WmNewsPageReqDto;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.pojo.WmMaterial;
import com.zhentao.pojo.WmNews;
import com.zhentao.pojo.WmUser;
import com.zhentao.service.WmMaterialService;
import com.zhentao.service.WmNewsMaterialService;
import com.zhentao.service.WmNewsService;
import com.zhentao.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Date 2024/2/27 19:34
 * @Author xdm
 **/
@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Resource
    private WmNewsMaterialService wamNewsMaterialService;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmMaterialService wmMaterialService;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的id
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //状态查询
        queryWrapper.lambda().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //频道查询
        queryWrapper.lambda().eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //关键字查询
        queryWrapper.lambda().like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //根据用户查询
        queryWrapper.lambda().eq(WmNews::getUserId, wmUser.getId());
        //按时间倒叙
        queryWrapper.lambda().orderByDesc(WmNews::getCreatedTime);
        //根据时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        page = wmNewsMapper.selectPage(page, queryWrapper);

        //3.返回结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }


    @Autowired
    WmNewsTaskService wmNewsTaskService;

    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.保存或者修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        // 处理文章类型
        if (dto.getType() == -1) {
            dto.setType((short) 4);
        }
        wmNews.setType(dto.getType());

        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);


        if (dto.getImages() != null && !dto.getImages().isEmpty()) {
            String imgStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imgStr);
        }


        if (wmNews.getId() == null) { // 新增
            wmNewsMapper.insert(wmNews);
        } else { // 修改
            wamNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            wmNewsMapper.updateById(wmNews);
        }

        // 绑定素材关系
        List<String> images = dto.getImages();
        if (images != null && !images.isEmpty()) {
            List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
            List<Integer> ids = new ArrayList<>();
            for (WmMaterial wmMaterial : wmMaterialList) {
                ids.add(wmMaterial.getId());
            }
            wmNewsMaterialMapper.saveMapper(ids, wmNews.getId(), (short) 0);
        }

        // 提取内容中的图片并绑定
        if (dto.getType() == 4) {
            List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);
            List<String> materials = new ArrayList<>();
            for (Map map : maps) {
                if ("image".equals(map.get("type"))) {
                    materials.add((String) map.get("value"));
                }
            }
            if (!materials.isEmpty()) {
                String imgs = StringUtils.join(materials, ",");
                wmNews.setImages(imgs);
                wmNewsMapper.updateById(wmNews);

                QueryWrapper<WmMaterial> wmMaterialQueryWrapper = new QueryWrapper<>();
                wmMaterialQueryWrapper.lambda().in(WmMaterial::getUrl, materials);
                List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(wmMaterialQueryWrapper);
                List<Integer> ids = new ArrayList<>();
                for (WmMaterial wmMaterial : wmMaterialList) {
                    ids.add(wmMaterial.getId());
                }
                wmNewsMaterialMapper.saveMapper(ids, wmNews.getId(), (short) 1);
            }
        }
// wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult downOrUp(WmNewsDownOrUpDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        wmNews.setEnable(dto.getEnable());
        wmNewsMapper.updateById(wmNews);

        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());

            //发送消息到kafka
            kafkaTemplate.send("articleDownOrUpTopic", JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}